package data

import (
	"errors"
	"gitee.com/yunduansing/limitsecondkill/model"
	"github.com/jmoiron/sqlx"
)

func FindStockByProductId(tx *sqlx.Tx,productId int) (data []model.StockEntity,err error) {
	sql:="select id,product_id,name,num from bt_stock where product_id=?"
	err=tx.Select(&data,sql,productId)
	return
}
func GetStockByProductId(db *sqlx.DB,productId int) (data []model.StockEntity,err error) {
	sql:="select id,product_id,name,num from bt_stock where product_id=?"
	err=db.Select(&data,sql,productId)
	return
}

func SubStock(tx *sqlx.Tx,productId int) (err error) {
	sql:="update bt_stock set num=num-1 where product_id=? and num>0"
	r,err:=tx.Exec(sql,productId)
	if err!=nil{
		return
	}
	if c,err:=r.RowsAffected();err==nil{
		if c==0{
			return errors.New("扣减失败，库存为0")
		}
	}
	return
}